package service.impl;

import dao.ClockRuleDao;
import dao.impl.ClockRuleDaoImpl;
import entity.ClockRule;
import service.ClockRuleService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ClockRuleServiceImpl implements ClockRuleService {
    private ClockRuleDao clockRuleDao = new ClockRuleDaoImpl();

    @Override
    public List<ClockRule> findAll() throws SQLException, ClassNotFoundException {
        return clockRuleDao.findAll();
    }

    @Override
    public ClockRule findById(Integer id) throws SQLException, ClassNotFoundException {
        return clockRuleDao.findById(id);
    }

    @Override
    public boolean save(ClockRule rule) throws SQLException, ClassNotFoundException {
        return clockRuleDao.save(rule);
    }

    @Override
    public boolean update(ClockRule rule) throws SQLException, ClassNotFoundException {
        return clockRuleDao.update(rule);
    }

    @Override
    public boolean delete(Integer id) throws SQLException, ClassNotFoundException {
        return clockRuleDao.delete(id);
    }

    @Override
    public boolean toggleStatus(Integer id, Boolean active) throws SQLException, ClassNotFoundException {
        return clockRuleDao.toggleStatus(id, active);
    }

    @Override
    public ClockRule extractRuleFromResultSet(ResultSet rs) throws SQLException {
        return clockRuleDao.extractRuleFromResultSet(rs);
    }

    public boolean isValidCheckInTime(Date checkInTime) throws SQLException, ClassNotFoundException {
        List<ClockRule> activeRules = clockRuleDao.findActiveRules();
        if (activeRules.isEmpty()) {
            return false; // 没有生效的规则
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(checkInTime);
        int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        int currentMinute = calendar.get(Calendar.MINUTE);

        for (ClockRule rule : activeRules) {
            LocalTime startTime = rule.getStartTime();
            LocalTime endTime = rule.getEndTime();

            if ((currentHour > startTime.getHour() ||
                    (currentHour == startTime.getHour() && currentMinute >= startTime.getMinute())) &&
                    (currentHour < endTime.getHour() ||
                            (currentHour == endTime.getHour() && currentMinute <= endTime.getMinute()))) {
                return true;
            }
        }
        return false;
    }

}